#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString hostip=GertLocalIpAddress();//获取服务器的IP地址
    ui->comboBox_IP->addItem(hostip);
    tcpserver=new QTcpServer(this);//负责哨兵的责任，负责监听新连接

    connect(tcpserver,&QTcpServer::newConnection,this,&MainWindow::newconnection);


}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::GertLocalIpAddress()
{
    QString hostaddress=QHostInfo::localHostName();
    QHostInfo hostinfo=QHostInfo::fromName(hostaddress);
    QList<QHostAddress> addresslist=hostinfo.addresses();
    QString localip="";
    for(int i=0;i<addresslist.size();i++)
    {
        QHostAddress tempip=addresslist.at(i);
        if(!addresslist.isEmpty())
        {
            if(tempip.protocol()==QAbstractSocket::IPv4Protocol)
            {
                localip=tempip.toString();
                break;
            }
        }
    }
    return localip;
}

void MainWindow::clientdisconnect()
{
   ui->plainTextEdit->appendPlainText("**********客户端socket断开连接**********");
   tcpsocket->deleteLater();
}
 void MainWindow::clientconnect()
 {
     ui->plainTextEdit->appendPlainText("**********客户端socket连接**********");
     ui->plainTextEdit->appendPlainText("**********peer address:"+
                                                tcpsocket->peerAddress().toString());
     ui->plainTextEdit->appendPlainText("**********peer port:"+
                                                QString::number(tcpsocket->peerPort()));
 }
 void  MainWindow::socketreaddata()
 {
       while(tcpsocket->canReadLine())
       {
           ui->plainTextEdit->appendPlainText("[in]:"+tcpsocket->readLine());
       }
 }
 void MainWindow::newconnection()
 {
     tcpsocket=tcpserver->nextPendingConnection();//获取套接字用于与新的客户端连接
     connect(tcpsocket,&QTcpSocket::connected,this,&MainWindow::clientconnect);//当有客户端连接上这个套接字就转到槽函数

     connect(tcpsocket,&QTcpSocket::disconnected,this,&MainWindow::clientdisconnect);//客户端断开连接触发信号

     connect(tcpsocket,&QTcpSocket::readyRead,this,&MainWindow::socketreaddata);//客户端发数据时触发

     connect(tcpsocket, &QTcpSocket::stateChanged, this,
             [this](QAbstractSocket::SocketState state) {
         // 直接在这里处理状态变化
         qDebug() << "Socket state changed to:" << state;
         // 其他处理逻辑
     });


 }


void MainWindow::on_pushButton_start_clicked()//打开监听
{
     QString ip=ui->comboBox_IP->currentText();
     quint16 port=ui->spinBox_port->value();
     QHostAddress address(ip);
     tcpserver->listen(address,port);//服务器监听这个ip和端口的状态，监听这个ip收到的连接

     ui->plainTextEdit->appendPlainText("$$$$$$$$$$开始监听$$$$$$$$$$");
     ui->plainTextEdit->appendPlainText("$$$$$$$$$$服务器地址$$$$$$$$$$："+
                                        tcpserver->serverAddress().toString());
     ui->plainTextEdit->appendPlainText("$$$$$$$$$$服务器端口$$$$$$$$$$："+
                                                QString::number(tcpserver->serverPort()));
     ui->pushButton_start->setEnabled(false);
     ui->pushButton_stop->setEnabled(true);
}

void MainWindow::on_pushButton_stop_clicked()//关闭监听
{
  if(tcpserver->isListening())
  {
      tcpserver->close();
      ui->plainTextEdit->appendPlainText("服务端断开");
      ui->pushButton_start->setEnabled(true);
      ui->pushButton_stop->setEnabled(false);
  }
}

void MainWindow::on_pushButton_send_clicked()
{
    QString strmsg=ui->lineEdit_message->text();
    ui->plainTextEdit->appendPlainText("[out]:"+strmsg);
    ui->lineEdit_message->clear();//清空输入框

    QByteArray msg=strmsg.toUtf8();//字符串转字节，适配中文
    msg.append("\n");//数据换行
    tcpsocket->write(msg);

}

void MainWindow::closeEvent(QCloseEvent *ev)
{
    if(tcpserver->isListening())
    {
        tcpserver->close();
    }
    ev->accept();

}
